<template>
  <view class="car">
<!--    <view class="me-head">-->
<!--      <u-sticky bgColor="#fff">-->
<!--        <u-tabs active-color="#f15929" :list="allList" :is-scroll="false" :current="form.order_type" @change="index => form.order_type = index"></u-tabs>-->
<!--      </u-sticky>-->
<!--    </view>-->
    <u-cell-group>
      <u-cell-item  @click="toAddress" v-if="checked" icon="map" :title="addressText">
        <div slot="label">
          <div class="u-box">
            <span class="name">{{ address.username  || ''}}</span>
            <span class="mobile">{{ address.phone || ''}}</span>
          </div>
        </div>
      </u-cell-item>
      <u-cell-item icon="clock" :title="checked ? '配送时间' : '自提时间'" :value="timeText" @click="toDate">
      </u-cell-item>
    </u-cell-group>
    <u-gap heigt="20"></u-gap>
    <div class="car-list">
      <div class="car-item" v-for="item in buyList" :key="item.id + item.spec_key" @click="toGoodDetail(item)">
        <u-image :src="item.image" :width="160" :height="160" mode="aspectFit"></u-image>
        <div class="goods-detail">
          <div class="goods-name">{{ item.name }}</div>
          <div class="goods-desc">{{ item.spec_key }}</div>
          <div class="goods-price-box">
            <div class="goods-price">￥{{ item.unit_price }}</div>
            <div class="goods-count">
              <span class="goods-count-value">x {{ item.count }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
<!--    <u-gap heigt="20"></u-gap>-->
<!--    <u-cell-group>-->
<!--      <u-cell-item  @click="toCoupon" title="优惠券" :value="couponText">-->
<!--      </u-cell-item>-->
<!--      <u-cell-item title="会员折扣" :value="userInfo.discount * 10 + '折'" :arrow="false">-->
<!--      </u-cell-item>-->
<!--      <u-cell-item :arrow="false">-->
<!--        <u-radio-group  active-color="#39b54a"  v-model="form.pay_type">-->
<!--          <u-radio name="wx" >微信支付</u-radio>-->
<!--        </u-radio-group>-->
<!--      </u-cell-item>-->
<!--    </u-cell-group>-->
    <div class="car-action">
      <div class="total">
        <span>合计：</span>
        <span class="total-value">￥{{ totalValue }}</span>
<!--        <div>-->
<!--          <div v-if="userInfo.discount" class="total-value2">会员优惠 ￥{{ totalValue * (userInfo.discount || 1) || 0 }}</div>-->
<!--          <div v-if="coupon.value" class="total-value2">优惠券 ￥{{ coupon.value || 0 }}</div>-->
<!--        </div>-->
      </div>
      <div>
        <div class="button button-primary" @click="openBuy">结算</div>

      </div>
    </div>
    <u-popup v-model="dateShow" mode="bottom" border-radius="14">
      <div class="date-picker-title">
        <span>选择时间</span>
        <span class="confirm-text" @click="confirmDate">确定</span>
      </div>
      <div class="date-picker-content">
        <div class="date-picker-slide">
          <div
              v-for="item in dayList"
              :key="item.day"
              @click="changeDay(item.value)"
              :class="['date-slide-item',item.value === activeDay ? 'active' :'']">
            {{ item.day }}
          </div>
        </div>
        <div class="date-time-list">
          <div
              @click="activeTime = item"
              :class="['date-time-item',item === activeTime ? 'active' :'']"
              v-for="item in timeList" :key="item">
            {{ item }}
          </div>
        </div>
      </div>
    </u-popup>
    <u-popup closeable v-model="payShow" mode="bottom" border-radius="14">
      <div class="publish-popup">
<!--        <div class="publish-item" @click="changePayWay(1)">-->
<!--          <image class="publish-icon" src="@/static/image/微信支付.png"></image>-->
<!--          <div class="publish-desc">-->
<!--            <div class="publish-name">微信支付</div>-->
<!--          </div>-->
<!--          <image v-if="form.pay_type === 1" class="publish-icon" src="@/static/image/radio_active.png"></image>-->
<!--          <image v-else class="publish-icon" src="@/static/image/radio.png"></image>-->
<!--        </div>-->
        <div class="publish-item" @click="changePayWay(2)">
          <image class="publish-icon" src="@/static/image/储值支付.png"></image>
          <div class="publish-desc" style="display: flex;align-items: center">
            <div class="publish-name">货到付款</div>
          </div>
          <image v-if="form.pay_type === 2" class="publish-icon" src="@/static/image/radio_active.png"></image>
          <image v-else class="publish-icon" src="@/static/image/radio.png"></image>
        </div>
        <div style="padding: 0 20rpx">
          <div style="width: 100%" class="button button-primary" @click="buyAll">确认支付</div>
        </div>
      </div>
    </u-popup>

    <!--    <u-keyboard-->
<!--        default=""-->
<!--        ref="uKeyboard"-->
<!--        mode="number"-->
<!--        :mask="true"-->
<!--        :mask-close-able="false"-->
<!--        :dot-enabled="false"-->
<!--        v-model="payShow"-->
<!--        :safe-area-inset-bottom="true"-->
<!--        :tooltip="false"-->
<!--        @change="onChange"-->
<!--        @backspace="onBackspace">-->
<!--      <view>-->
<!--        <div style="display: flex;align-items: center;justify-content: center;position:relative;width: 100%;">-->
<!--          <div style="text-align: center;font-weight: bold;font-size: 32rpx;padding: 20rpx 0">微信支付</div>-->
<!--          <view class="u-padding-10 close" data-flag="false" @tap="showPop(false)">-->
<!--            <u-icon name="close" color="#333333" size="28"></u-icon>-->
<!--          </view>-->
<!--        </div>-->
<!--        <view class="u-text-center u-padding-20 money">-->
<!--          <text>{{ totalValue }}</text>-->
<!--          <text class="u-font-20 u-padding-left-10">元</text>-->

<!--        </view>-->
<!--        <view class="u-flex u-row-center">-->
<!--          <u-message-input-->
<!--              mode="box"-->
<!--              :maxlength="6"-->
<!--              :dot-fill="true"-->
<!--              v-model="password"-->
<!--              :disabled-keyboard="true"-->
<!--              @finish="finish"-->
<!--          ></u-message-input>-->
<!--        </view>-->
<!--        <view class="u-text-center u-padding-top-10 u-padding-bottom-20 tips">支付键盘</view>-->
<!--      </view>-->
<!--    </u-keyboard>-->

  </view>
</template>

<script>
import dayjs from 'dayjs'
import recharge from "../recharge/recharge.vue";
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      baseUrl: this.$baseUrl,
      allList: [
        {tabId: 0,name: '配送'},
        {tabId: 1,name: '自提'},
      ],
      buyList: [
      ],
      address: {},
      coupon: {},
      dateShow: false,
      activeDay: dayjs().format('YYYY-MM-DD'),
      activeTime: '08:00-08:30',
      // 日期 今天 明天 后天 计算具体月日
      dayList: [
        {id: 0, day: `今天${dayjs().format('MM月DD日')}`, value: dayjs().format('YYYY-MM-DD')},
        {id: 1, day: `明天${dayjs().add(1, 'day').format('MM月DD日')}`, value: dayjs().add(1, 'day').format('YYYY-MM-DD')},
        {id: 2, day: `后天${dayjs().add(2, 'day').format('MM月DD日')}`, value: dayjs().add(2, 'day').format('YYYY-MM-DD')},
      ],
      timeList: [

      ],
      form: {
        address_id: '',
        member_id: '',
        order_type: 0,
        day: '',
        time: '',
        pay_type: 2,
        coupon_id: ''
      },
      userInfo: uni.getStorageSync('userInfo') || {},
      payShow: false,
      password:'',
      balance: '0.00'
    }
  },
  computed: {
    recharge() {
      return recharge
    },
    checked() {
      return this.form.order_type === 0
    },
    getRegionName() {
      return this.address.region ? JSON.parse(this.address.region).map(el => el.label).join('') : ''
    },
    addressText() {
      return this.address.id ? `${this.getRegionName}${this.address.address} -${this.address.code}` : '请选择地址'
    },
    timeText() {
      if (!this.form.day || !this.form.time) {
        return '请选择时间'
      }
      // 如果是当天 显示今天 08:00-08:30
      if (this.form.day === dayjs().format('YYYY-MM-DD')) {
        return `今天 ${this.activeTime}`
      }
      return `${dayjs(this.form.day).format('MM月DD日')} ${this.form.time}`
    },
    couponText() {
      return this.coupon.id ? this.coupon.name : '请选择优惠券'
    },
    totalValue() {
      let value = this.buyList.reduce((total, el) => {
        total += (el.unit_price * el.count)
        return total
      }, 0)
      return value
    },
    ...mapGetters(['userInfo']),
    isCompany() {
      return this.userInfo && this.userInfo.company_id
    }
  },
  onLoad() {
    this.buyList = uni.getStorageSync('buyList') || []
    console.log(this.buyList)
    // 根据当前时间计算日期 如果超过晚上8点 则默认选择明天 并且仅展示明天的列表
    const hour = dayjs().hour()
    if (hour >= 20) {
      this.activeDay = dayjs().add(1, 'day').format('YYYY-MM-DD')
      this.dayList = [
        {id: 0, day: `明天${dayjs().add(1, 'day').format('MM月DD日')}`, value: dayjs().add(1, 'day').format('YYYY-MM-DD')},
        {id: 1, day: `后天${dayjs().add(2, 'day').format('MM月DD日')}`, value: dayjs().add(2, 'day').format('YYYY-MM-DD')},
      ]
    } else {
      this.activeDay = dayjs().format('YYYY-MM-DD')
      this.dayList = [
        {id: 0, day: `今天${dayjs().format('MM月DD日')}`, value: dayjs().format('YYYY-MM-DD')},
        {id: 1, day: `明天${dayjs().add(1, 'day').format('MM月DD日')}`, value: dayjs().add(1, 'day').format('YYYY-MM-DD')},
        {id: 2, day: `后天${dayjs().add(2, 'day').format('MM月DD日')}`, value: dayjs().add(2, 'day').format('YYYY-MM-DD')},
      ]
    }
  },
  methods: {
    changePayWay(val) {
      if (val === 2) {
        if (Number(parseFloat(this.balance) || 0) > this.totalValue) {
          this.form.pay_type = val
        } else {
          uni.showToast({
            title: '余额不足',
            icon: 'none'
          })
        }
      }
      if (val === 1) {
        this.form.pay_type = val
      }
    },
    onChange(val){
      if(this.password.length<6){
        this.password += val;
      }

      if(this.password.length>=6){
        this.pay();
      }
    },

    onBackspace(e){
      if(this.password.length>0){
        this.password = this.password.substring(0,this.password.length-1);
      }
    },
    showPop(flag = true){
      this.password = '';
      this.payShow = flag;
    },
    finish(){
      console.log(11111)
    },
     pay(){
      uni.showLoading({
        title:'支付中'
      })
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/pay/success'
        })
      }, 500)
    },
    // 设置优惠券
    setCoupon(item) {
      const total = this.buyList.reduce((total, el) => {
        total += el.price * el.count
        return total
      }, 0)

      if (total < item.mini_value) {
        uni.showToast({
          title: '未达到优惠券使用条件',
          icon: 'none'
        })
        return false
      }
      //当前时间不在优惠券时间范围内不可用
      if (dayjs().isBefore(item.start_time) || dayjs().isAfter(item.end_time)) {
        uni.showToast({
          title: '优惠券不在使用时间范围内',
          icon: 'none'
        })
        return false
      }
      this.coupon = item
      return true
    },
    openBuy() {
      if (!this.userInfo.id) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      if (!this.buyList.length) {
        uni.showToast({
          title: '请选择商品',
          icon: 'none'
        })
        return
      }
      if (!this.address.id) {
        uni.showToast({
          title: '请先选择地址',
          icon: 'none'
        })
        return
      }
      if (!this.form.day || !this.form.time) {
        uni.showToast({
          title: '请选择时间',
          icon: 'none'
        })
        return
      }
      this.$api.memberDetail(this.$store.state.userInfo.id).then((res) => {
        this.balance = res.balance || '0.00';
        this.payShow = true
      });
    },
    buyAll() {
      let that = this
      this.$api.orderCreate({
        member_id: this.userInfo.id,
        member_name: this.userInfo.nickname,
        address_id: this.address.id,
        address: this.addressText,
        address_nickname: this.address.username,
        address_phone: this.address.phone,
        send_time: `${this.form.day} ${this.form.time}`,
        pay_type: this.form.pay_type,
        amount: this.totalValue,
        count: this.buyList.reduce((total, el) => {
          total += el.count
          return total
        }, 0),
        order_status: 0,
        status: this.form.pay_type,
        goods: this.buyList.map(el => {
          return {
            goods_id: el.id,
            goods_name: el.name,
            goods_desc: el.desc,
            goods_image: el.image,
            goods_price: el.price,
            spec_key: el.spec_key,
            spec_check: el.spec_check,
            count: el.count,
            amount: el.totalPrice
          }
        }),
      }).then(res => {
        uni.setStorageSync('buyList', [])
        if (this.form.pay_type === 1) {
          wx.requestPayment({
            timeStamp: res.timestamp,
            nonceStr: res.nonce_str,
            package: res.package,
            signType: res.signType,
            paySign: res.paySign,
            success () {
              uni.redirectTo({
                url: '/pages/pay/success'
              })
            },
            fail (res) {
              console.log('pay fail', res)
              uni.redirectTo({
                url: '/pages/order/order'
              })
            }
          })
        } else {
          uni.redirectTo({
            url: '/pages/pay/success'
          })
        }
      })
    },
    toAddress() {
      uni.navigateTo({
        url: '/pages/address/address?source=1'
      })
    },
    toGoodDetail(item) {

    },
    toDate() {
      this.dateShow = true
      this.activeDay = this.form.day
      this.activeTime = this.form.time
      this.changeDay(this.activeDay || this.dayList[0].value)
    },
    changeDay(value) {
      this.activeDay = value
      let timeList = []
      // 如果activeDay是当天 则只能选择当前时间之后的时间 如果是后天 则可以选择所有时间
      const now = dayjs().format('YYYY-MM-DD')
      if (value === now) {
        // 当天根据当前时间计算
        const hour = dayjs().hour()
        const minute = dayjs().minute()
        let start = 8
        if (hour > 8) {
          start = hour
          if (minute > 30) {
            start++
          }
        }

        for (let i = start; i < 21; i++) {
          timeList.push(`${i}:00-${i}:30`)
          timeList.push(`${i}:30-${i+1}:00`)
        }
      } else {
        // 非当天 使用循环插入时间 早上8点到晚上8点
        for (let i = 8; i < 21; i++) {
          timeList.push(`${i}:00-${i}:30`)
          timeList.push(`${i}:30-${i+1}:00`)
        }
      }
      this.timeList = timeList
      this.activeTime = timeList[0]

    },
    confirmDate() {
      this.dateShow = false
      this.form.day = this.activeDay
      this.form.time = this.activeTime
      console.log(this.form)
    },
    toCoupon() {
      uni.navigateTo({
        url: '/pages/coupon/index?source=1'
      })
    }
  }
}
</script>

<style lang="scss">
.car {
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding-bottom: 120rpx;
  height: 100%;
  background-color: #ffffff;
  .date-picker-content {
    height: 500rpx;
    overflow: hidden;
    display: flex;
    background-color: rgb(242, 242, 242);
    .date-picker-slide {
      flex-shrink: 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      .date-slide-item {
        font-size: 28rpx;
        color: #333333;
        padding: 13px 43px 13px 30px;
        &.active {
          background-color: #ffffff;
        }
      }
    }
    .date-time-list {
      height: 100%;
      flex-grow: 1;
      overflow: auto;
      background-color: #ffffff;
      .date-time-item {
        flex-shrink: 0;
        line-height: 80rpx;
        font-size: 28rpx;
        color: #333333;
        text-align: center;
        margin-bottom: 10px;
        &.active {
          color: #f15929
        }
      }
    }
  }
  .handle-head {
    background-color: #FFFFFF;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    line-height: 80rpx;
    font-size: 32rpx;
    color: #dd6161;
    padding: 0 14px;
  }
  .car-list {
    .car-item {
      position: relative;
      box-sizing: border-box;
      padding: 16rpx 32rpx;
      color: #323233;
      font-size: 24rpx;
      background-color: #FFFFFF;
      border-bottom: 1px solid #f7f8fa;
      display: flex;
      .goods-detail {
        margin-left: 10px;
        flex-grow: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        .goods-name {
          font-size: 28rpx;
          color: #000000;
          margin-bottom: 10px;
        }
        .goods-price-box {
          margin-top: 10px;
          display: flex;
          justify-content: space-between;
          .goods-price {
            color: #f15929;
            font-size: 28rpx;
          }
          .goods-count {
            display: flex;
            .goods-count-value{
              margin: 0 10px;
              font-size: 36rpx;
            }
          }
        }
      }
    }
  }
  .car-action {
    position: fixed;
    bottom: 50rpx;
    left: 0;
    flex-shrink: 0;
    width: 100%;
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #FFFFFF;
    color: #FFFFFF;
    box-sizing: border-box;
    padding: 0 14px;
    .car-btn {

    }
    .total {
      color: #000000;
      display: flex;
      align-items: center;
    }
    .total-value {
      color: #f15929;
      margin-right: 15px;
      font-size: 32rpx;
    }
    .total-value2 {
      color: #aeaeae;
      font-size: 24rpx;
    }
  }
  .date-picker-title {
    padding: 17px 15px;
    background-color: rgb(242, 242, 242);
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 28rpx;
    color: #333333;
    .confirm-text {
      color: #f15929;
    }
  }

  .publish-popup {
    padding-top: 80rpx;
    padding-bottom: 60rpx;
    .publish-item {
      height: 110rpx;
      display: flex;
      align-items: center;
      padding: 20rpx 10rpx;
      border-radius: 24rpx;
      margin-bottom: 20rpx;
      border-bottom: 1px solid #f0f0f0;
      .publish-icon {
        width: 60rpx;
        height: 60rpx;
        margin-right: 20rpx;
        margin-left: 20rpx;
      }
      .publish-desc {
        flex-grow: 1;
        height: 100%;
        .publish-name {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }
        .publish-sub {
          font-size: 24rpx;
          color: #999999;
          margin-top: 10rpx;
        }
      }
    }
  }

}
</style>
